﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using ViewMaker.Core;
using ViewMaker.Core.Utils;
using ViewMaker.Core.ViewModels;
using ViewMaker.Core.Silverlight;

namespace ViewMaker.Core.Views
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class ViewLayoutView : UserControl
    {

        public ViewLayoutViewModel targetViewModel { get; set; }
        private ViewLayoutItem nextPost;

        public ViewLayoutView()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ViewLayoutView_Loaded);
        }

        /// <summary>
        /// LoadedのタイミングでViewModelと親ウインドウのイベントをワイヤーする
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ViewLayoutView_Loaded(object sender, RoutedEventArgs e)
        {
            targetViewModel = (ViewLayoutViewModel)this.DataContext;
            targetViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ViewModel_PropertyChanged);
        }

        private void File_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                var cmd = (string)((ComboBoxItem)e.AddedItems[0]).Content;
                if (cmd == "Show XAML") targetViewModel.ShowXamlCommand.Execute(null);
                if (cmd == "Show Layout") targetViewModel.ShowLayoutViewerCommand.Execute(null);
                if (cmd == "Close") targetViewModel.CloseCommand.Execute(null);
                File.SelectedIndex = -1;
            }
        }


        #region TreeView操作

        void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "CurrentItem" && targetViewModel.CurrentItem != null)
            {
                var tvi = FindTreeViewItem(targetViewModel.CurrentItem);
                if (tvi != null) tvi.IsSelected = true;
            }
        }

        private TreeViewItem FindTreeViewItem(ViewLayoutItem item)
        {
            TreeViewItem tvi = null;
            if (item.Parent == null)
            {
                tvi = (TreeViewItem)treeView.ItemContainerGenerator.ContainerFromItem(item);
            }
            else
            {
                var parent = FindTreeViewItem(item.Parent);
                if (parent != null) tvi = (TreeViewItem)parent.ItemContainerGenerator.ContainerFromItem(item);
            }
            if (tvi != null)
            {
                tvi.IsExpanded = true;
                tvi.UpdateLayout();
            }
            return tvi;
        }

        private void TreeViewItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var fe = sender as FrameworkElement;
            if (fe == null) return;
            var item = FindTreeViewItem(fe);
            if (item != null)
            {
                this.treeView.SelectItem(item);
                item.IsSelected = true;
            }
        }

        private TreeViewItem FindTreeViewItem(DependencyObject fe)
        {
            if (fe == null) return null;
            if (fe is TreeViewItem) return (TreeViewItem)fe;
            return FindTreeViewItem(VisualTreeHelper.GetParent(fe));
        }

        private void AddControlListCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.targetViewModel.CurrentItem == null) return;

            if (AddControlListCombo.SelectedItem != null)
            {
                this.targetViewModel.AddControlCommand.Execute(AddControlListCombo.SelectedItem);
                AddControlListCombo.SelectedIndex = -1;
            }
        }

        private void AddItemListCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.targetViewModel.CurrentItem == null) return;

            if (AddItemListCombo.SelectedItem != null)
            {
                this.targetViewModel.GenerateItemCommand.Execute(AddItemListCombo.SelectedItem);
                AddItemListCombo.SelectedIndex = -1;
            }

        }

        private void treeView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                if (this.targetViewModel.CurrentItem == null) return;
                this.targetViewModel.RemoveItemCommand.Execute(null);
                SetNextPosition(this.targetViewModel.CurrentItem);
                e.Handled = true;
            }
        }

        private void SetNextPosition(ViewLayoutItem next)
        {
            nextPost = next;
            this.Dispatcher.BeginInvoke(() =>
            {
                nextPost = null;
                this.targetViewModel.CurrentItem = null;
                this.targetViewModel.CurrentItem = next;
                this.treeView.Focus();
            });
        }

        private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (nextPost != null) return;
            targetViewModel.CurrentItem = e.NewValue as ViewLayoutItem;
        }

        #endregion


    }
}
